// utils/request.js

// 基础配置
const config = {
	baseURL: 'http://120.79.170.227:5000', // 接口根地址线上 http://120.79.170.227:5000 本地http://localhost:5000
	timeout: 15000, // 超时时间（毫秒）
	loading: true // 是否显示加载动画
}

// 请求拦截器
const requestInterceptor = (options) => {
	// 显示加载动画
	if (options.loading) {
		uni.showLoading({
			title: '加载中...'
		})
	}

	// 添加全局header（如token）
	options.header = {
		...options.header,
		'Authorization': `Bearer ${uni.getStorageSync('token') || ''}`
	}

	return options
}

// 响应拦截器
const responseInterceptor = (response, options) => {
	// 隐藏加载动画
	if (options.loading) {
		uni.hideLoading()
	}

	const [error, res] = response
	const {
		statusCode,
		data
	} = res

	// 全局错误处理
	if (error || statusCode !== 200) {
		uni.showToast({
			title: res.data.message || '网络请求失败',
			icon: 'none'
		})
		
		if(statusCode === 430){
			uni.removeStorageSync('token');
			setTimeout(()=>{
				uni.reLaunch({
					url:'/pages/login/login'
				});
			});
		}
		
		return Promise.reject(error || new Error('请求失败'))
	}

	// 业务状态码处理（根据后端约定调整）
	switch (data.code) {
		case 200:
			return data
			break;
		case 430:
			uni.showToast({
				title: '登录状态过期请重新登录！',
				icon: 'none'
			});
			return Promise.reject(data)
			break;
		default:
			uni.showToast({
				title: data.msg || '业务错误',
				icon: 'none'
			});
			return Promise.reject(data)
	}
}

// 核心请求方法
const request = (method, url, data, options = {}) => {
	// 合并配置
	const mergedOptions = {
		...config,
		...options,
		method
	}

	// 执行请求拦截器
	const processedOptions = requestInterceptor(mergedOptions)

	return new Promise((resolve) => {
		uni.request({
			url: config.baseURL + url,
			data,
			method,
			header: processedOptions.header,
			timeout: processedOptions.timeout,
			success: (res) => resolve([null, res]),
			fail: (err) => resolve([err, null])
		})
	}).then(response => responseInterceptor(response, mergedOptions))
}

// 快捷方法封装
const http = {
	get: (url, params, options) => request('GET', url, params, options),
	post: (url, data, options) => request('POST', url, data, options),
	put: (url, data, options) => request('PUT', url, data, options),
	delete: (url, data, options) => request('DELETE', url, data, options)
}

export default http